﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Heritage.Codebox;
using Heritage.Logging;
using Heritage.Models;
using System.Threading;
using System.IO;

namespace Heritage.Controllers
{
    public class HomeController : BaseController
    {
        [AuthorizedValidated]
        public ActionResult Photo(string id)
        {
            return new ImageResult(id, false);
        }

        public ActionResult SmallPhoto(string id)
        {
            return new ImageResult(id, true);
        }

        
        [AuthorizedValidated]
        public ActionResult Personal(string id)
        {
            Users user;
            if (string.IsNullOrEmpty(id)) user = Utils.GetCurrentUser();
            else user = Utils.GetUserByID(id);
            if (user == null)
            {
                LogService.Error(Utils.GetPrincipalName(), Constants.COMPONENT_SITE, string.Format("Home/Personal: User not found: {0}", id));
            }
            Session["CurrentGuid"] = user.ID.ToString("N");
            PersonalData data = Utils.GetPersonalDataByID(user.ID);
            PersonalModel model = new PersonalModel();
            //data.About = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
            model.About = data.About??"<span style=\"text-align:center\">нет данных</span>";
            model.Birthdate = data.Birthdate != null? data.Birthdate.Value.ToShortDateString() : "засекречено";
            model.City = data.City??"засекречено";
            model.ContactMail = data.ContactMail??"засекречено";
            model.GameNicks = data.Nicknames??"засекречено";
            model.Hobbies = data.Hobbies??"засекречено";
            model.ICQ = data.ICQ??"засекречено";
            model.PersonalRating = data.PersonalRating.ToString();
            model.ServerRating = data.GameRating.ToString();
            model.Since = Utils.GetFirstGameName(user.ID)??"";
            model.Skype = data.Skype ?? "засекречено";
            model.Username = user.Username;
            model.Played = ""+Utils.GetPlayedGames(user.ID);
            model.UserID = user.ID.ToString("N");
            DateTime? lastVisit = Utils.GetLastVisit(user.ID);
            if (lastVisit != null && (DateTime.Now - (DateTime)lastVisit).TotalMinutes < 15)
            {
                model.Icons = "<img src=\"/Images/Icons/tag_green.png\" title=\"Онлайн\"/>";
            }
            else
            {
                model.Icons = "<img src=\"/Images/Icons/tag_red.png\" title=\"Оффлайн\"/>";
            }

            model.Icons += Utils.GetRibbons(user.ID);

            switch (user.UserRole) {
                case Constants.USER_ROLE_BANNED: model.Icons += "<img src=\"/Images/Icons/user_delete.png\" title=\"Забанен\"/>";
                    break;
                case Constants.USER_ROLE_TESTER: model.Icons += "<img src=\"/Images/Icons/tux.png\" title=\"Тестовый пользователь\"/>";
                    break;
                case Constants.USER_ROLE_JUNIOR: model.Icons += "<img src=\"/Images/Icons/user_orange.png\" title=\"Новичок\"/>";
                    break;
                case Constants.USER_ROLE_NORMAL: model.Icons += "<img src=\"/Images/Icons/user.png\" title=\"Пользователь\"/>";
                    break;
                case Constants.USER_ROLE_SENIOR: model.Icons += "<img src=\"/Images/Icons/user_red.png\" title=\"Ветеран\"/>";
                    break;
                case Constants.USER_ROLE_MODERATOR: model.Icons += "<img src=\"/Images/Icons/user_policeman.png\" title=\"Модератор\"/>";
                    break;
                case Constants.USER_ROLE_ADMIN: model.Icons += "<img src=\"/Images/Icons/administrator.png\" title=\"Администратор\"/>";
                    break;
                case Constants.USER_ROLE_GAMEMASTER: model.Icons += "<img src=\"/Images/Icons/user_zorro.png\" title=\"Гейм-мастер\"/>";
                    break;
                default:
                    break;
            }

            ViewData.Model = model;
            return View();
        }

        [AuthorizedValidated]
        public ActionResult JoinGame()
        {
            return View();
        }

        [AuthorizedValidated]
        public ActionResult ActiveGames()
        {
            return View();
        }
        
        public ActionResult SwitchMenuPanel(string Hidden) 
        {
            HeritageEntities ents = new HeritageEntities();
            Users us = ents.Users.Where(r => r.Username == Thread.CurrentPrincipal.Identity.Name).FirstOrDefault();
            if (us != null)
            {
                us.MenuCollapsed = false;
                if (Hidden == "hide")
                {
                    us.MenuCollapsed = true;
                }
                ents.SaveChanges();
            }
            return null;
        }

        [AuthorizedValidated]
        public ActionResult AllMyGames()
        {
            return View();
        }

        [AuthorizedValidated]
        [NoCache]
        public ActionResult SwitchSpecMode()
        {
            HeritageEntities ents = new HeritageEntities();
            Users us = ents.Users.Where(r => r.Username == Thread.CurrentPrincipal.Identity.Name).FirstOrDefault();
            if (us != null)
            {
                us.SpecialMode = 1 - us.SpecialMode;
                ents.SaveChanges();
            }
            return new RedirectResult(Request.UrlReferrer.AbsoluteUri);
        }

        [AuthorizedValidated]
        public ActionResult Feedback()
        {
            return View();
        }

        [AuthorizedValidated]
        public ActionResult FeedbackSent()
        {
            return View();
        }

        [AuthorizedValidated]
        public ActionResult UploadPhoto()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [AuthorizedValidated]
        public ActionResult Feedback(FormCollection coll)
        {
            if (string.IsNullOrEmpty(coll["message"]))
            {
                ModelState.AddModelError("err", "Надо бы хоть чего-нить все-таки написать, мм?");
                return View();
            }
            Utils.SocialMessageCreate(Constants.ADRESAT_GAMEMASTER, Constants.SOCIALMESSAGE_TYPE_GAME_FEEDBACK, "Сообщение из раздела \"Обратная связь\"", Utils.GetStrippedText(coll["message"]));
            return new RedirectResult("/Home/FeedbackSent");
        }

        [AuthorizedValidated]
        public ActionResult EditInfo()
        {
            HeritageEntities ents = new HeritageEntities();
            Users me = Utils.GetCurrentUser();
            PersonalData data = ents.PersonalData.Where(r => r.UserID == me.ID).First();
            PersonalModel model = new PersonalModel();
            model.Gender = data.Gender?? true;
            model.About = data.About??"";
            model.Birthdate = data.Birthdate != null?data.Birthdate.Value.ToString("dd.MM.yyyy") : "";
            model.City = data.City??"";
            model.ContactMail = data.ContactMail??"";
            model.Hobbies = data.Hobbies??"";
            model.ICQ = data.ICQ??"";
            model.Skype = data.Skype??"";
            model.GameNicks = data.Nicknames ?? "";
            ViewData.Model = model;
            return View();
        }
        [AcceptVerbs(HttpVerbs.Post)]
        [AuthorizedValidated]
        public ActionResult EditInfo(FormCollection coll) 
        {
            HeritageEntities ents = new HeritageEntities();
            Users me = Utils.GetCurrentUser();
            PersonalModel model = new PersonalModel();            
            model.Gender = coll["gender"] == "W";
            model.About = coll["about"];
            DateTime bdate = DateTime.MinValue;
            if (!string.IsNullOrEmpty(coll["birthdate"]) && !DateTime.TryParse(coll["birthdate"], out bdate))
            {
                model.Birthdate = coll["birthdate"];
                ViewData.ModelState.AddModelError("err","Введите дату рождения в формате 'дд.мм.гггг', или просто оставьте поле пустым, если не хотите ее указывать");
            }
            model.City = coll["city"];
            model.ContactMail = coll["email"];
            //model.Hobbies = data.Hobbies;
            model.ICQ = coll["icq"];
            model.Skype = coll["skype"];
            model.GameNicks = coll["nicknames"];
            if (!ViewData.ModelState.IsValid)
            {
                ViewData.Model = model;
                return View();                
            }
            else
            {
                PersonalData data = ents.PersonalData.Where(r => r.UserID == me.ID).First();
                data.About = string.IsNullOrEmpty(model.About.Trim())? null : model.About;
                data.Birthdate = string.IsNullOrEmpty(coll["birthdate"])? (DateTime?)null : bdate;
                data.City = string.IsNullOrEmpty(model.City.Trim()) ? null : model.City;
                data.ContactMail = string.IsNullOrEmpty(model.ContactMail.Trim()) ? null : model.ContactMail;
                data.Gender = model.Gender;
                data.ICQ = string.IsNullOrEmpty(model.ICQ.Trim()) ? null : model.ICQ;
                data.Skype = string.IsNullOrEmpty(model.Skype.Trim()) ? null : model.Skype;
                data.Nicknames = string.IsNullOrEmpty(model.GameNicks.Trim()) ? null : model.GameNicks;
                ents.SaveChanges();
                return new RedirectResult("/");
            }
        }
        [AcceptVerbs(HttpVerbs.Post)]
        [AuthorizedValidated]
        public ActionResult PersonalFeedback(FormCollection coll)
        {
            Guid userid = Guid.Parse(coll["userid"]);
            bool priv = coll["private"] != null;
            string fbtext = coll["fbtext"];
            if (!string.IsNullOrEmpty(fbtext))
            {
                fbtext = fbtext.Replace("\n", "<br>");
                HeritageEntities ents = new HeritageEntities();
                Utils.SocialMessageCreate(userid, priv? Constants.SOCIALMESSAGE_TYPE_PERSONAL_FEEDBACK_PRIVATE : Constants.SOCIALMESSAGE_TYPE_PERSONAL_FEEDBACK_PUBLIC, (priv?"Приватный отзыв ":"Отзыв ")+"от пользователя "+Utils.GetCurrentUser().Username+"!", fbtext);
                string text =
                    string.Format(
                        "Здравствуйте, {0}!\n\nВам был оставлен новый отзыв на вашей персональной странице игрового сервера netmafia.ru\n\n\nУспехов,\nпочтовый робот сервера netmafia.ru",
                        Utils.GetUserByID(userid.ToString("N")).Username);
                Utils.SendMail(Utils.GetUserByID(userid.ToString("N")).Email,"Новый отзыв на вашей страничке!", text);
            }
            return new RedirectResult("/Home/Personal/" + coll["userid"]);
        }

    }
    class ImageResult : ActionResult
    {
        private string uid;
        private bool small;

        public ImageResult(string uid, bool small)
        {
            this.uid = uid;
            this.small = small;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            HeritageEntities ents = new HeritageEntities();
            try
            {
                Guid g = Guid.Parse(uid);
                byte[] all = ents.PersonalData.Where(r => r.UserID == g).Select(t => t.Photo).First();
                if (all.Length == 0) throw new Exception("emtpy picture");
                if (small)
                {
                    Image img = Image.FromStream(new MemoryStream(all));
                    Bitmap resized = new Bitmap(img, img.Width/2, img.Height/2);
                    MemoryStream ms = new MemoryStream();
                    resized.Save(ms, ImageFormat.Png);
                    all = ms.ToArray();
                }
                context.HttpContext.Response.ContentType = "image/png";
                context.HttpContext.Response.OutputStream.Write(all, 0, all.Length);
                return;
            }
            catch (Exception ex)
            {
                FileStream f = File.OpenRead(context.HttpContext.Server.MapPath(small ? "/images/nophoto_small.png" : "/images/nophoto.png"));
                byte[] all = new byte[f.Length];
                f.Read(all, 0, all.Length);
                context.HttpContext.Response.ContentType = "image/png";
                context.HttpContext.Response.OutputStream.Write(all, 0, all.Length);
                return;
            }
        }
    }
}
